package New;

class MovieTicket{
    int number = 50;
    public synchronized void saleTicker(){
        if (number>0){
            System.out.println(Thread.currentThread().getName()+"\t"+"-----卖出第："+number--);
        }else{
            System.out.println("-----卖光了");
        }
    }
}
class  House{

        ThreadLocal<Integer> threadLocal = ThreadLocal.withInitial(()->0);
        public void saleHouse(){
            Integer value = threadLocal.get();
            ++value;
            threadLocal.set(value);
        }
}
public class ThreadLocalDemo {
    public static void main(String[] args) {
        MovieTicket movieTicket = new MovieTicket();
//        for (int i = 1;i<=3;i++){
//            new Thread(()->{
//                for (int j = 0; j <=20; j++) {
//                    movieTicket.saleTicker();
//                }
//            },String.valueOf(i)).start();
//        }
        House house = new House();
        new Thread(()->{
            try {
                for (int i = 1; i <=3; i++) {
                    house.saleHouse();
                }
                System.out.println(Thread.currentThread().getName()+"\t"+"---卖出："+house.threadLocal.get());
            } catch (Exception e) {
                e.printStackTrace();
            } finally {
                house.threadLocal.remove();//每次使用完了必须remove，避免内存泄漏
            }
        },"t1").start();
        new Thread(()->{
            try {
                for (int i = 1; i <=5; i++) {
                    house.saleHouse();
                }
                System.out.println(Thread.currentThread().getName()+"\t"+"---卖出："+house.threadLocal.get());
            } catch (Exception e) {
                e.printStackTrace();
            } finally {
                house.threadLocal.remove();
            }
        },"t2").start();
        new Thread(()->{
            try {
                for (int i = 1; i <=8; i++) {
                    house.saleHouse();
                }
                System.out.println(Thread.currentThread().getName()+"\t"+"---卖出："+house.threadLocal.get());
            } catch (Exception e) {
                e.printStackTrace();
            } finally {
                house.threadLocal.remove();
            }
        },"t3").start();
        System.out.println(Thread.currentThread().getName()+"\t"+"---卖出："+house.threadLocal.get());
    }
}
